package csx.study.demo.service.impl;

import cn.hutool.Hutool;
import cn.hutool.core.util.IdUtil;
import csx.study.demo.dto.Result;
import csx.study.demo.dto.UserDTO;
import csx.study.demo.entity.SeckillVoucher;
import csx.study.demo.entity.User;
import csx.study.demo.entity.VoucherOrder;
import csx.study.demo.mapper.VoucherMapper;
import csx.study.demo.mapper.VoucherOrderMapper;
import csx.study.demo.service.ISeckillVoucherService;
import csx.study.demo.service.IVoucherOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import csx.study.demo.utils.UserHolder;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.concurrent.ListenableFutureCallback;

import java.time.LocalDateTime;
import java.util.Collections;

//TODO redis优惠券预检
//TODO mq异步生成订单
/**
 * <p>
 *  优惠券下单
 * </p>
 *
 * @author csx
 * @since 2025-03-03
 */
@Service
public class VoucherOrderServiceImpl extends ServiceImpl<VoucherOrderMapper, VoucherOrder> implements IVoucherOrderService {

    @Autowired
    private ISeckillVoucherService seckillVoucherService;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Lazy
    @Autowired
    private IVoucherOrderService proxy;

    private static final DefaultRedisScript<Long> SECKILL_SCRIPT;
    static {
        SECKILL_SCRIPT = new DefaultRedisScript<>();
        SECKILL_SCRIPT.setLocation(new ClassPathResource("seckill.lua"));
        SECKILL_SCRIPT.setResultType(Long.class);
    }

    @Override
    public Result seckillVoucher(Long voucherId) {
        //1.执行lua脚本，判断当前用户的购买资格
        Long userId = UserHolder.getUser().getId();
        long result = stringRedisTemplate.execute(
                SECKILL_SCRIPT,
                Collections.emptyList(),
                voucherId.toString(), userId.toString());
        if (result != 0) {
            //2.不为0说明没有购买资格
            return Result.fail(result==1?"库存不足":"不能重复下单");
        }
        //3.有购买资格，将订单信息存到消息队列
        VoucherOrder voucherOrder = new VoucherOrder();

        //雪花算法
        Long orderId = IdUtil.getSnowflake().nextId();
        voucherOrder.setId(orderId);
        voucherOrder.setUserId(UserHolder.getUser().getId());
        voucherOrder.setVoucherId(voucherId);

        //4. 存入消息队列等待异步消费
        // 4.1 创建CorrelationData
        CorrelationData cd = new CorrelationData();
        cd.getFuture().whenComplete((confirm, throwable) -> {
            if (throwable != null) {
                log.error("消息发送失败，发生异常!", throwable);
            } else {
                if (confirm.isAck()) {
                    log.debug("消息发送成功，收到ack!");
                } else {
                    log.error("消息发送失败，收到nack! 原因: " + confirm.getReason());
                }
            }
        });

        rabbitTemplate.convertAndSend("lvan.direct","direct.seckill",voucherOrder);
        return Result.ok(orderId);
    }

    /**
     * rabbitmq异步秒杀
     *
     */
    @Transactional
    @Override
    public void handleVoucherOrder(VoucherOrder voucherOrder) {
        //1.所有信息从当前消息实体中拿
        // 获取用户
        Long userId = voucherOrder.getUserId();
        //创建锁对象
        RLock redisLock = redissonClient.getLock("lock:order:"+userId);
        //尝试获取锁
        boolean isLock = redisLock.tryLock();

        //4.判断是否获取锁成功
        if(!isLock){
            //获取锁失败，直接返回失败或者重试
            log.error("不允许重复下单！");
            return;
        }


        //串行消费，不需要分布式锁
        //代理调用保证事务
        proxy.createVoucherOrder(voucherOrder);

        //如果是并发消费，还是要分布式锁
//        try{
//            proxy.createVoucherOrder(voucherOrder);
//        }finally {
//            if (redisLock.isHeldByCurrentThread()) {
//                redisLock.unlock();
//            }
//        }

    }

    @Transactional
    @Override
    public void createVoucherOrder(VoucherOrder voucherOrder) {

        Long voucherId = voucherOrder.getVoucherId();
        //一人一单判断
        Long userId=voucherOrder.getUserId();

        Long count=lambdaQuery().eq(VoucherOrder::getUserId,userId).eq(VoucherOrder::getVoucherId,voucherId).count();
        if(count>0){
            return;
        }

        boolean success = seckillVoucherService.update()
                .setSql("stock= stock -1") // set stock = stock -1
                .eq("voucher_id", voucherId)
                .gt("stock",0)// where id = ? and stock > 0
                .update();
        if (!success) {
            //扣减库存
            log.error("库存不足！");
            return ;
        }
        save(voucherOrder);
    }

//    @Override
//    public Result seckillVoucher(Long voucherId) {
//
//        //查询秒杀优惠券信息
//        SeckillVoucher seckillVoucher=seckillVoucherService.getById(voucherId);
//
//        //判空
//        if(seckillVoucher==null){
//            return Result.fail("指定优惠券不存在");
//        }
//
//        //判断是否在指定时间段内
//        if(LocalDateTime.now().isBefore(seckillVoucher.getBeginTime())){
//            return Result.fail("秒杀还没开始");
//        }
//
//        if(LocalDateTime.now().isAfter(seckillVoucher.getEndTime())){
//            return Result.fail("秒杀已经结束");
//        }
//
//        //判断库存是否充足
//        if(seckillVoucher.getStock()<=0){
//            return Result.fail("库存不足");
//        }
//
//        Long userId = UserHolder.getUser().getId();
//
//        //锁不能放在事务中，避免锁释放和事务提交之间的间隙出现并发问题
//        RLock lock = redissonClient.getLock("lock:order:" + userId);
//        if (!lock.tryLock()) {
//            return Result.fail("请勿重复请求");
//        }
//
//        try {
//            VoucherOrderServiceImpl proxy = (VoucherOrderServiceImpl) AopContext.currentProxy();
//            return proxy.createVoucherOrder(voucherId);
//        } finally {
//            lock.unlock();
//        }
//
//    }
//
//    @Override
//    @Transactional
//    public Result createVoucherOrder(Long voucherId) {
//
//        Long userId=UserHolder.getUser().getId();
//
//        Long count=lambdaQuery().eq(VoucherOrder::getUserId,userId).eq(VoucherOrder::getVoucherId,voucherId).count();
//        if(count>0){
//            return Result.fail("不允许重复下单");
//        }
//
//        //扣减库存
//        boolean success= seckillVoucherService
//                .lambdaUpdate()
//                .eq(SeckillVoucher::getVoucherId, voucherId)
//                //乐观锁，判断库存是否大于0
//                .gt(SeckillVoucher::getStock, 0)
//                .setSql("stock = stock - 1")
//                .update();
//
//        if(!success){
//            return Result.fail("扣减库存失败");
//        }
//
//        //创建订单，订单需要订单ID，优惠券ID，用户ID
//        VoucherOrder voucherOrder=new VoucherOrder();
//
//        //雪花算法全局唯一ID
//        Long orderId=IdUtil.getSnowflake().nextId();
//        voucherOrder.setId(orderId);
//
//        //优惠券ID
//        voucherOrder.setVoucherId(voucherId);
//
//        //用户ID，从ThreadLocal里拿
//        voucherOrder.setUserId(UserHolder.getUser().getId());
//
//        save(voucherOrder);
//
//        return Result.ok(orderId);
//
//
//    }


}
